package com.example.mvt;


import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.LightingColorFilter;
import android.graphics.PorterDuff;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.Toast;

public class Vote extends Activity {
	
	String username;
	String id;
	String look="0";
	String build="0";
	String deliver="0";
	String can="0";
	String assume="0";
	/*Button button= (Button) findViewById(R.id.submit);
	CheckBox look= (CheckBox) findViewById(R.id.look);
	CheckBox build= (CheckBox) findViewById(R.id.build);
	CheckBox deliver= (CheckBox) findViewById(R.id.deliver);
	CheckBox can= (CheckBox) findViewById(R.id.can);
	CheckBox assume= (CheckBox) findViewById(R.id.assume);*/
	
	
	private static final String PHP_GET = "http://webdev.cs.uwosh.edu/students/meyers11/PHPGetAll.php";
	private static final String PHP_CHECK = "http://webdev.cs.uwosh.edu/students/meyers11/PHPCheck.php";
	private static final String PHP_TALLY = "http://webdev.cs.uwosh.edu/students/meyers11/PHPTally.php";
	ArrayList<Employee> empslist = new ArrayList<Employee>();
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vote);
		new GetEmps().execute();
		
		findViewById(R.id.submit).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						new TallyVote().execute();
					}
				});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.vote, menu);
		return true;
	}
	
	//Get Login Info
	private class getLoginInfo extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... nothing) {
			
			MVTDataSource mds2 = new MVTDataSource(Vote.this);
			
			mds2.open();
			
			try {
				username = mds2.getUsername();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			mds2.close();
			
			return username;
		}
		
		@Override
		protected void onPostExecute(String whatever) {
			if (username.equals("user")){
				Intent myIntent = new Intent(Vote.this, LoginActivity.class);
				startActivityForResult(myIntent, 0);
				return;
			}
			else{
				return;
			}
		}
		
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		new getLoginInfo().execute();
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
	    // Handle item selection
	    switch (item.getItemId()) {	
	        case R.id.action_logout:
	        	new Logout().execute();
	        	Intent myIntent3 = new Intent(Vote.this, LoginActivity.class);
				startActivityForResult(myIntent3, 0);
				Vote.this.finish();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	private class GetEmps extends AsyncTask<Void, Void, ArrayList<Employee>>{
		@Override
		protected ArrayList<Employee> doInBackground(Void... nothing) {
			ArrayList<Employee> emps = new ArrayList<Employee>();
			String response = "";
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_GET);
				try
				{
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					response = httpClient.execute(httppost, respondHandler);
					System.out.println("HELLOOO" + response);

					//Parse JSON Data
					int id;
					String position = "";
					String name = "";
					String phone = "";

					try{

						JSONArray jArray = new JSONArray(response);
						
						JSONObject json_data = null;

						for(int i = 0; i < jArray.length(); i++)
						{
							json_data = jArray.getJSONObject(i);
							
							position = json_data.getString("position");
							id = Integer.parseInt(json_data.getString("id"));
							name = json_data.getString("name");
							phone = json_data.getString("phone");
							
							Employee e = new Employee(id,name,phone,position,"default");
							emps.add(e);
						}
						
					}catch(JSONException e1){
						e1.printStackTrace();
						System.out.println("HELLO JSON error: " + e1);
					}
				}
				catch(Exception e){
					System.out.println("HELLO connection error: " + e);
					
				}
			}
			
			empslist = emps;
			return emps;
		}
		
		@Override
		protected void onPostExecute(ArrayList<Employee> list) {
			Spinner spinner = (Spinner) findViewById(R.id.empspin);
    		ArrayAdapter<Employee> adapter =  new ArrayAdapter<Employee>(Vote.this, android.R.layout.simple_spinner_dropdown_item, list);
    		spinner.setAdapter(adapter);
		}
		
	}
	
	//Logout
	private class Logout extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... nothing) {
			
			MVTDataSource mds2 = new MVTDataSource(Vote.this);
			
			mds2.open();
			
			try {
				mds2.logoutUser();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			mds2.close();
			
			return "";
		}
		
		@Override
		protected void onPostExecute(String whatever) {
				Intent myIntent = new Intent(Vote.this, LoginActivity.class);
				startActivityForResult(myIntent, 0);
				Vote.this.finish();
		}
		}
		
		private class TallyVote extends AsyncTask<Void, Void, String>{
			@Override
			protected String doInBackground(Void... nothing) {
				String response = "";
				
				ConnectivityManager connMgr1 = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo1 = connMgr1.getActiveNetworkInfo();
				
				if(networkInfo1 != null && networkInfo1.isConnected())
				{
					
					ArrayList<NameValuePair> n1 = new ArrayList<NameValuePair>(1);
					n1.add(new BasicNameValuePair("username", username));
					
					HttpClient httpClient1 = new DefaultHttpClient();
					HttpPost httppost1 = new HttpPost(PHP_CHECK);
					try
					{
						httppost1.setEntity(new UrlEncodedFormEntity(n1));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient1.execute(httppost1, respondHandler);
						response = response.trim();
						System.out.println("HELLOOO000" + response + username);

					}
					catch(Exception e2){
						System.out.println("HELLO connection error: " + e2);
						
					}
				}
				
				
				return response;
			}
			@Override
			protected void onPostExecute(String response) {
				if(response.equals("true")){
					System.out.println("HELLO");
					Context context = getApplicationContext();
					Toast.makeText(context, "You have already voted this month", Toast.LENGTH_SHORT).show();
					Intent myIntent = new Intent(Vote.this, MainActivity.class);
					startActivityForResult(myIntent, 0);
					Vote.this.finish();
				}
				else{
					new TallyVote2().execute();
				}
			}
			
		
	}
		
		private class TallyVote2 extends AsyncTask<Void, Void, String>{
			@Override
			protected String doInBackground(Void... nothing) {
				String response = "";
				Employee e = new Employee();
				CheckBox look1= (CheckBox) findViewById(R.id.look);
				CheckBox build1= (CheckBox) findViewById(R.id.build);
				CheckBox deliver1= (CheckBox) findViewById(R.id.deliver);
				CheckBox can1= (CheckBox) findViewById(R.id.can);
				CheckBox assume1= (CheckBox) findViewById(R.id.assume);
				
				Spinner spin= (Spinner) findViewById(R.id.empspin); 
				e = (Employee) spin.getItemAtPosition(spin.getSelectedItemPosition());
				
				id = Integer.toString(e.getId());
				
				if (look1.isChecked()){
					look = "1";
				}
				if(build1.isChecked()){
					build="1";
				}
				if(deliver1.isChecked()){
					deliver="1";
				}
				if(can1.isChecked()){
					can="1";
				}
				if(assume1.isChecked()){
					assume="1";
				}
				
				ConnectivityManager connMgr1 = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo1 = connMgr1.getActiveNetworkInfo();
				
				if(networkInfo1 != null && networkInfo1.isConnected())
				{
					
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
					n.add(new BasicNameValuePair("username", username));
					n.add(new BasicNameValuePair("look", look));
					n.add(new BasicNameValuePair("build", build));
					n.add(new BasicNameValuePair("deliver", deliver));
					n.add(new BasicNameValuePair("can", can));
					n.add(new BasicNameValuePair("assume", assume));
					n.add(new BasicNameValuePair("id", id));
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(PHP_TALLY);
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);
						response = response.trim();
						System.out.println("HIII" +response);
					}
					catch(Exception e2){
						System.out.println("HELLO connection error: " + e2);
						
					}
				}
				
				return response;
			}
			@Override
			protected void onPostExecute(String response) {
				if(response.equals("true")){
					Context context = getApplicationContext();
					Toast.makeText(context, "Vote Tallied Successfully", Toast.LENGTH_SHORT).show();
					Intent myIntent = new Intent(Vote.this, MainActivity.class);
					startActivityForResult(myIntent, 0);
					Vote.this.finish();
				}
				else{
					Context context = getApplicationContext();
					CharSequence text = "Issue with vote, please try again";
					int duration = Toast.LENGTH_SHORT;
				
					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
				}
			}
			
		
	}

}

